package com.fa.wisdom.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.coder.zzq.smartshow.dialog.LoadingDialog;
import com.fa.wisdom.R;
import com.fa.wisdom.base.BaseFragment;
import com.fa.wisdom.ui.JKActivity;
import com.fa.wisdom.ui.QiuzhuJLActivity;
import com.fa.wisdom.ui.StaticActivity;
import com.fa.wisdom.utils.Loading;
import com.fa.wisdom.utils.PermissionUtils;
import com.fa.wisdom.utils.ScreenUtil;
import com.fa.wisdom.utils.SpUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class ManagerFragment extends BaseFragment implements View.OnClickListener{
    View statusBarPlace;
    public LocationClient mLocationClient = null;
    private LinearLayout ll_jiankangxinxi, ll_yongyaojilu,ll_guijichaxun,ll_sos;
    private boolean isFirst = true;
    TextView tv_wd,tv_1,tv_detail;
    ImageView titleLeft;
    TextView titleMid;
    private static final String[] PERMISSIONS_CONTACT = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ll_jiankangxinxi=view.findViewById(R.id.ll_jiankangxinxi);
        ll_yongyaojilu=view.findViewById(R.id.ll_yongyaojilu);
        ll_guijichaxun=view.findViewById(R.id.ll_guijichaxun);
        ll_sos=view.findViewById(R.id.ll_sos);
        ll_jiankangxinxi.setOnClickListener(this);
        ll_yongyaojilu.setOnClickListener(this);
        ll_guijichaxun.setOnClickListener(this);
        ll_sos.setOnClickListener(this);

        titleLeft = view.findViewById(R.id.title_left);
        titleMid = view.findViewById(R.id.title_mid);
        titleLeft.setVisibility(View.GONE);
        titleMid.setText("健康");
        tv_wd=view.findViewById(R.id.tv_wd);
        tv_1=view.findViewById(R.id.tv_1);
        tv_detail=view.findViewById(R.id.tv_detail);
        statusBarPlace = view.findViewById(R.id.view_status_bar_place);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getPermission();
        } else {
            if (mLocationClient != null)
                mLocationClient.stop();
        }
    }


    /**
     * 定位
     */
    private void startLocate() {
        //定位初始化
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(requireActivity().getApplicationContext());

            //通过LocationClientOption设置LocationClient相关参数
            LocationClientOption option = new LocationClientOption();

            option.setIsNeedAddress(true);
            //可选，是否需要地址信息，默认为不需要，即参数为false
            //如果开发者需要获得当前点的地址信息，此处必须为true

            option.setNeedNewVersionRgc(true);
            //可选，设置是否需要最新版本的地址信息。默认需要，即参数为true

            //设置locationClientOption
            mLocationClient.setLocOption(option);
            //注册LocationListener监听器
            MyLocationListener myLocationListener = new MyLocationListener();
            mLocationClient.registerLocationListener(myLocationListener);
        }
        //开启地图定位图层
        mLocationClient.start();
    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
        PermissionUtils.getInstance().checkPermissions(requireActivity(), PERMISSIONS_CONTACT, permissionsResult);
    }

    //创建监听权限的接口对象
    PermissionUtils.IPermissionsResult permissionsResult = new PermissionUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //当提示申请权限时，全部通过，会走这里（6.0以下直接走这里）
            startLocate();
        }

        @Override
        public void forbitPermissons() {
            //只要有一个被拒绝，则会走这里，拒绝不在提醒，还是会走这里
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        PermissionUtils.getInstance().onRequestPermissionsResult(requireActivity(), requestCode, permissions, grantResults);
    }

    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_manager, null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_jiankangxinxi://健康信息
                startActivity(new Intent(requireActivity(), JKActivity.class));
                break;
            case R.id.ll_yongyaojilu://用药记录
                break;
            case R.id.ll_guijichaxun://轨迹查询
                startActivity(new Intent(requireActivity(), StaticActivity.class));
                break;
            case R.id.ll_sos://求助记录
                startActivity(new Intent(requireActivity(), QiuzhuJLActivity.class));
                break;
        }
    }


    public  class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
//            String addr = location.getAddrStr();    //获取详细地址信息
//            String country = location.getCountry();    //获取国家
//            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
//            String district = location.getDistrict();    //获取区县
//            String street = location.getStreet();    //获取街道信息
//            String adcode = location.getAdCode();    //获取adcode
//            String town = location.getTown();    //获取乡镇信息
            if (!TextUtils.isEmpty(city))
                getWeather(city.replaceAll("市", ""));
            else
                getWeather("洛阳");
        }
    }

    //获取天气信息
    private  void getWeather(String city) {
        String url = "http://apis.juhe.cn/simpleWeather/query";
        String key = "5acd6f1b5f62501253eb209b39d43ac6";
        LoadingDialog dialog= Loading.getInstance().onShowLargeLoading("努力加载中...");
        dialog.showInActivity(requireActivity());
        OkHttpUtils.get().url(url).addParams("key", key).addParams("city", city).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                e.printStackTrace();
                dialog.dismiss();
                tv_wd.setText( SpUtils.getInstance().decodeString("wd","35")+"°");
                tv_1.setText( SpUtils.getInstance().decodeString("info","晴天"));
                tv_detail.setText(SpUtils.getInstance().decodeString("detail","东北风1级"));
            }

            @Override
            public void onResponse(String response, int id) {
                dialog.dismiss();
                JSONObject jsonObject= JSON.parseObject(response);
                JSONObject jsonObject1=jsonObject.getJSONObject("result");
                JSONObject jsonObject2= jsonObject1.getJSONObject("realtime");
                String wd=jsonObject2.getString("temperature");//溫度
                String info=jsonObject2.getString("info");
                String detail=jsonObject2.getString("direct")+jsonObject2.getString("power");
                tv_wd.setText(wd+"°");
                tv_1.setText(info);
                tv_detail.setText(detail);
                SpUtils.getInstance().encode("wd",wd);
                SpUtils.getInstance().encode("info",info);
                SpUtils.getInstance().encode("detail",detail);
            }
        });
    }

    //健康信息
}
